package qdu.guisockets.clientlet;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class TestSocketClient {
    private Socket s;
    private BufferedWriter bw;
    private BufferedReader br;

    public void connetToServer(){
        try {
            s = new Socket(LoginFrame.SERVERIP, LoginFrame.SERVERPORT);
            bw = new BufferedWriter(
                new OutputStreamWriter(s.getOutputStream())
            );
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            new ClientUI(this).initUI();
        } catch (UnknownHostException e) {
            System.out.println("服务器地址有误"); System.exit(0); //e.printStackTrace();
        } catch (IOException e) {
            System.out.println("网络流建立失败"); System.exit(0); //e.printStackTrace();
        } 
    }
    public void disconnectFromServer(){
        try {
            if(s!=null && !s.isClosed()){
                s.close();
            }
            if(bw !=null){
                bw.close();
            }
            if(br != null)
                br.close();
        } catch (Exception e) { 
            System.out.println("关闭连接失败"); System.exit(0); //e.printStackTrace(); 
        }
    }
    public String getMessageFromServer() throws IOException{
        String message = "";        
        message = br.readLine();
        if(message != null && !"".equals(message.trim())){
            message = message.trim();
        }        
        return message;
    }
    public void sendMessageToServer(String message){
        try { 
            bw.write(message.trim() + '\n');
            bw.flush();              
        }catch (Exception e) {
            System.out.println("发送消息异常~");
            e.printStackTrace();
        }
    }    
    public Socket getSocket(){
        return this.s;
    }
    public BufferedWriter getBw(){
        return this.bw;
    }
}
